package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.commom.Result;
import com.example.demo.entity.*;
import com.example.demo.entity.LendRecord;
import com.example.demo.entity.LendRecord;
import com.example.demo.mapper.LendRecordMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/LendRecord")
public class LendRecordController {
    @Resource
    LendRecordMapper LendRecordMapper;

    @DeleteMapping("/{isbn}")
    public Result<?> delete(@PathVariable String isbn) {
        Map<String, Object> map = new HashMap<>();
        map.put("isbn", isbn);
        LendRecordMapper.deleteByMap(map);
        return Result.success();
    }

    //删除一条记录
    @PostMapping("/deleteRecord")
    public Result<?> deleteRecord(@RequestBody LendRecord LendRecord) {
        Map<String, Object> map = new HashMap<>();
        map.put("isbn", LendRecord.getIsbn());
        map.put("borrownum", LendRecord.getBorrownum());
        LendRecordMapper.deleteByMap(map);
        return Result.success();
    }

    @PostMapping("/deleteRecords")
    public Result<?> deleteRecords(@RequestBody List<LendRecord> LendRecords) {
        int len = LendRecords.size();
        for (int i = 0; i < len; i++) {
            LendRecord curRecord = LendRecords.get(i);
            Map<String, Object> map = new HashMap<>();
            map.put("isbn", curRecord.getIsbn());
            map.put("borrownum", curRecord.getBorrownum());
            LendRecordMapper.deleteByMap(map);
        }
        return Result.success();
    }

    @PostMapping
    public Result<?> save(@RequestBody LendRecord LendRecord) {
        LendRecordMapper.insert(LendRecord);
        return Result.success();
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search1,
                              @RequestParam(defaultValue = "") String search2,
                              @RequestParam(defaultValue = "") String search3,
                              @RequestParam(required = false) String startDate,
                              @RequestParam(required = false) String endDate
    ) {
        LambdaQueryWrapper<LendRecord> wrappers = Wrappers.<LendRecord>lambdaQuery();
        if (StringUtils.isNotBlank(search1)) {
            wrappers.like(LendRecord::getIsbn, search1);
        }
        if (StringUtils.isNotBlank(search2)) {
            wrappers.like(LendRecord::getBookname, search2);
        }
        if (StringUtils.isNotBlank(search3)) {
            wrappers.like(LendRecord::getReaderId, search3);
        }
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            wrappers.between(LendRecord::getLendTime,startDate, endDate);
        }
        Page<LendRecord> LendRecordPage = LendRecordMapper.selectPage(new Page<>(pageNum, pageSize), wrappers);
        return Result.success(LendRecordPage);
    }

    @GetMapping("/reader/{readerId}")
    public Result<?> findAllRecord(@PathVariable String readerId) {
        // 构建查询条件
        LambdaQueryWrapper<LendRecord> wrapper = Wrappers.<LendRecord>lambdaQuery();
        wrapper.eq(LendRecord::getReaderId, readerId);

        // 直接查询所有匹配记录
        List<LendRecord> records = LendRecordMapper.selectList(wrapper);

        // 返回结果
        return Result.success(records);
    }

    @PutMapping("/{isbn}")
    public Result<?> update(@PathVariable String isbn, @RequestBody LendRecord lendRecord) {
        UpdateWrapper<LendRecord> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("isbn", isbn);
        LendRecord lendrecord = new LendRecord();
        lendrecord.setLendTime(lendRecord.getLendTime());
        lendrecord.setReturnTime(lendRecord.getReturnTime());
        lendrecord.setStatus(lendRecord.getStatus());
        LendRecordMapper.update(lendrecord, updateWrapper);
        return Result.success();
    }

    @PutMapping("/{lendTime}")
    public Result<?> update2(@PathVariable Date lendTime, @RequestBody LendRecord lendRecord) {
        UpdateWrapper<LendRecord> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("lendTime", lendTime);
        LendRecord lendrecord = new LendRecord();
        lendrecord.setReturnTime(lendRecord.getReturnTime());
        lendrecord.setStatus(lendRecord.getStatus());
        LendRecordMapper.update(lendrecord, updateWrapper);
        return Result.success();
    }

    // 确保路径变量名一致
    @GetMapping("/Borrow/{id}/{status}/{bookName}")
    public Result<?> searchUserCurrentBorrow(@PathVariable String id,
                                             @PathVariable Integer status,
                                             @PathVariable String bookName) {
        // 校验参数
        if (StringUtils.isBlank(id)) {
            return Result.error("400", "用户ID不能为空");
        }

        try {
            // 明确状态码的含义：0表示当前借阅，1表示历史借阅
            // 假设status=0查询未归还的记录，status=1查询已归还的记录
            LambdaQueryWrapper<LendRecord> wrapper = Wrappers.<LendRecord>lambdaQuery()
                    .eq(LendRecord::getReaderId, id)
                    .eq(LendRecord::getStatus, status);
            if (!"none".equals(bookName)) {
                wrapper.eq(LendRecord::getBookname, bookName);
            }
            List<LendRecord> records = LendRecordMapper.selectList(wrapper);
            return Result.success(records);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("500", "查询借阅记录失败");
        }
    }
}
